

#include "Line_RG_Demo/Public/DemoGameMode.h"

#include "DemoCharacter.h"
#include "LineReplicationGraphObject.h"
#include "GameFramework/Character.h"

void ADemoGameMode::InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage)
{
	Super::InitGame(MapName, Options, ErrorMessage);

	UReplicationDriver::CreateReplicationDriverDelegate().BindLambda([](UNetDriver* ForNetDriver, const FURL& URL, UWorld* World) -> UReplicationDriver*
	{
		return  NewObject<ULineReplicationGraph>(GetTransientPackage());
	});
	
	SpawnCharacter();
}

void ADemoGameMode::StartPlay()
{
	Super::StartPlay();
}

void ADemoGameMode::SpawnCharacter()
{
	if(SpawnInterval <= 0)
	{
		UE_LOG(LogTemp, Error, TEXT("ADemoGameMode::SpawnCharacter Error SpawnInterval %f"), SpawnInterval)
		return;
	}
	if(!CharacterClass)
	{
		CharacterClass = ADemoCharacter::StaticClass();
	}
	FVector LocationStart = SpawnStart;
	FVector LocationEnd = SpawnEnd;
	LocationStart.X = FMath::Min(SpawnStart.X, SpawnEnd.X);
	LocationStart.X = FMath::Min(SpawnStart.Y, SpawnEnd.Y);
	LocationEnd.X = FMath::Max(SpawnStart.X, SpawnEnd.X);
	LocationEnd.X = FMath::Max(SpawnStart.Y, SpawnEnd.Y);
	FVector Location = LocationStart;

	UWorld* World = GetWorld();
	int32 CurrentId = 1;
	while (Location.X <= LocationEnd.X)
	{
		while (Location.Y <= LocationEnd.Y)
		{
			ADemoCharacter* Character = Cast<ADemoCharacter>(
				 World->SpawnActor(CharacterClass, &Location, nullptr) );
			Character->SetId(CurrentId);
			CurrentId ++;
			Location.Y += SpawnInterval;
		}
		Location.X += SpawnInterval;
		Location.Y = LocationStart.Y;
	}
}